import { createStore } from 'vuex'
import { User,StoreState } from './type'
import {ProjectConfig} from "@/config";
import { setHeader } from '@/config';

export default createStore<StoreState>({
  state: {
    user:{},
    isLogin:false
  },
  mutations: {
    setUser(state,newUser: User){
      // 页面刷新时自动设置user信息，达到免登录
      state.user = newUser;
      state.isLogin = true;
      localStorage.setItem(ProjectConfig.SESSION_USER,JSON.stringify(newUser));
      setHeader(ProjectConfig.HEADER_TOKEN_NAME,newUser.sessionId);
    },
    logout(state){
      state.user = {};
      state.isLogin = false;
      localStorage.removeItem(ProjectConfig.SESSION_USER);
      localStorage.removeItem(ProjectConfig.LAST_LOGIN_TIME);
      setHeader(ProjectConfig.HEADER_TOKEN_NAME,'');
    },
  },
  getters: {
    isLogin(state):boolean{
      return state.isLogin;
    },
    getUser(state): User{
      return (state.user as User);
    }
  },
  actions: {
  }
})
